import requests
import re
import mysql.connector



conn = mysql.connector.connect(
  host="localhost",       # 数据库主机地址
  port=3366,              #端口号，默认3306
  user="root",            # 数据库用户名
  passwd="123",            # 数据库密码
  database='qq_music'
)

sname = input('please input a keyword for what you want to download: ')
fp = 'E:/download/music/'
cmd = conn.cursor()
sql = 'select song_name,song_mid,singer_name,id from songlist where singer_name like \'%'+\
      str(sname)+'%\' or song_name like \'%'+str(sname)+'%\' or album_name like \'%'+str(sname)+'%\' limit 0,10'
# sql = 'select song_name,song_mid,singer_name,id from songlist where id=620450'
cmd.execute(sql)
data = cmd.fetchall()
conn.close()

headers = {'User-Agent':
               'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 '
               ' (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
           'Referer':
               'https://y.qq.com/n/yqq/album/004CEoOk010kXJ.html',
           'Accept':
               'application/json, text/javascript, */*; q=0.01'
           }
requests.packages.urllib3.disable_warnings()
mid = []
seq = 0
for item in data :
    seq = seq +1
    print(str(seq)+'.',str(item[0]),'--'+str(item[2]),'--'+str(item[3]))
    mid.append(item[1])
if len(data):
    num =  input('please input the sequence number you want to download: ')
    num = re.findall(r'\d+',num)
else:
    print('there is no information for you.')
    quit()
for i in num :
    song_mid = mid[int(i)-1]  # uin=0a
    urlp = 'https://u.y.qq.com/cgi-bin/musicu.fcg?data={"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"4531032572","songmid":["'+str(song_mid)+'"],"songtype":[0],"uin":"1323351502","loginflag":1,"platform":"20"}},"comm":{"uin":1323351502,"format":"json","ct":24,"cv":0}}'
    rp = requests.session().get(urlp,headers=headers,verify=False)
    song_purl = rp.json()['req_0']['data']['midurlinfo'][0]['purl']
    url = 'http://58.49.111.20/amobile.music.tc.qq.com/'+song_purl
    r=requests.get(url,headers=headers,verify=False)
    # print(purl)
    if len(url) > 50 :
        pt = re.sub(re.compile('\?.*'),'',url)
        pt = re.sub(re.compile('.*/C4'),'',pt)
        with open(fp+pt,"wb") as f:
            f.write(r.content)
        print('download successfully.')
    else :
        print("the song's information has an error.")
    
# & D:/CS/conda/envs/python3/python.exe e:/ProgramLanguageStudy/python/ML/qq_load.py
